package com.hxht.cmp.websocket;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hxht.cmp.entity.User;
import com.hxht.cmp.mapper.UserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.server.standard.SpringConfigurator;
import tk.mybatis.mapper.entity.Example;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;


@ServerEndpoint(value = "/recordPlayList", configurator = SpringConfigurator.class)
public class PlayList {
    private Logger logger = LoggerFactory.getLogger(PlayList.class);
    @Autowired
    private UserMapper userMapper;

    private static final List<Session> sessions;
    private static List<Map<String, Object>> cmpPlayList;

    static {
        sessions = new ArrayList<>();
        cmpPlayList = Collections.synchronizedList(new ArrayList<Map<String, Object>>());
    }


    @OnMessage
    public void onMessage(String message, Session session) throws IOException, InterruptedException {
        Map<String, Object> obj = new Gson().fromJson(message, new TypeToken<Map<String, Object>>() {
        }.getType());
        String userName = (String) obj.get("userName");
        String planUid = (String) obj.get("planUid");
        String type = (String) obj.get("type");
        String caseNo = (String) obj.get("caseNo");
        String caseName = (String) obj.get("caseName");
        String courtUid = (String) obj.get("courtUid");

        //信息先和原有记录进行比较，以userId和planId为主键，(其实没有必要)
        for (Map<String, Object> oldRecord : cmpPlayList) {
            if (oldRecord.get("userName").equals(userName) && oldRecord.get("planUid").equals(planUid)) {
                return;
            }
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Map<String, Object> recordPlay = new HashMap<>();
        recordPlay.put("uid", session.getId());
        recordPlay.put("userName", userName);
        recordPlay.put("planUid", planUid);
        recordPlay.put("type", type);
        recordPlay.put("caseNo", caseNo);
        recordPlay.put("caseName", caseName);
        recordPlay.put("startTime", format.format(new Date()));
        if ("super".equals(userName)) {
            recordPlay.put("realName","超级管理员");
            recordPlay.put("userUid","FC91B14EEF9C58C4CAD8FDF87B4C0BEA");
        }else{
            Example example = new Example(User.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("courtUid", courtUid);
            criteria.andEqualTo("username",userName);
            List<User> users = userMapper.selectByExample(example);
            recordPlay.put("realName",users.get(0).getRealName());
            recordPlay.put("userUid",users.get(0).getUid());
        }

        cmpPlayList.add(recordPlay);
    }

    @OnOpen
    public void onOpen(Session session) {
        System.out.println("Connection build");
    }

    @OnClose
    public void onClose(Session session) {
        System.out.println("Connection closed");
        Iterator<Map<String, Object>> listIter = cmpPlayList.iterator();
        while (listIter.hasNext()) {
            Map<String, Object> record = listIter.next();
            if (Objects.deepEquals(session.getId(), record.get("uid"))) {
                listIter.remove();//这里要使用Iterator的remove方法移除当前对象，如果使用List的remove方法，则同样会出现ConcurrentModificationException
            }
        }
    }

    public static void sendMessage(String message) throws IOException {
        for (Session session : sessions) {
            session.getBasicRemote().sendText(message);//同步
        }
    }

    public static List<Map<String, Object>> getCmpPlayList() {
        return cmpPlayList;
    }
}
